package com.sgb.kjwl.view.ui.activity.demand;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import androidx.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityDemandPublishBinding;
import com.sgb.kjwl.di.home.DaggerHomeComponent;
import com.sgb.kjwl.di.home.HomeModule;
import com.sgb.kjwl.model.entity.DemandGoodsEntity;
import com.sgb.kjwl.model.entity.DemandPublishEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.view.event.self.DemandEvent;
import com.sgb.kjwl.view.ui.adapter.home.AddGoodsAdapter;
import com.swgk.core.view.CityPickBuilder;
import com.swgk.core.view.CityPickView;
import com.swgk.core.dialog.RoundCornerDialog;
import com.sgb.kjwl.viewmodel.demand.DemandPublishModel3;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.util.MToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import javax.inject.Inject;

import static com.swgk.core.event.EventConstant.EVENT_ADD_GOOGS;

/**
 * Description:
 * Author CFK
 * Time
 */
public class DemandPublishActivity extends AppActivity {
    private String no;
    private int type;
    private ActivityDemandPublishBinding binding;
    private AddGoodsAdapter addGoodsAdapter;
    private LinearLayoutManager linearLayoutManager;
    private List<DemandGoodsEntity> demandGoodsEntityList;
    private DemandPublishEntity demandPublishEntity;
    // 一级联动数据
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;
    // 二级联动数据
    private List<List<AddressEntity<List<AddressEntity>>>> opt2;
    // 三级联动数据
    private List<List<List<AddressEntity>>> opt3;
    private boolean isLoaded = false;
    private int cityPosition1;
    private int cityPosition2;
    private int cityPosition3;
    private Calendar selectedDate;
    @Inject
    DemandPublishModel3 viewModel;

    public static void start(Context context, DemandPublishEntity demandPublishEntity) {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putSerializable("demandPublishEntity", demandPublishEntity);
        intent.putExtras(bundle);
        intent.setClass(context, DemandPublishActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected boolean statusBarDark() {
        return true;
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerHomeComponent.builder().appComponent(appComponent).homeModule(new HomeModule(this)).build().inject(this);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void initView() {
        demandPublishEntity = (DemandPublishEntity) getIntent().getSerializableExtra("demandPublishEntity");
        binding = DataBindingUtil.setContentView(DemandPublishActivity.this, R.layout.activity_demand_publish);
        binding.setViewModel(viewModel);
        binding.include.ivBack.setOnClickListener(this);
        binding.llAdd.setOnClickListener(this);
        binding.llTime.setOnClickListener(this);
        binding.llAddress.setOnClickListener(this);
        binding.tvPublish.setOnClickListener(this);
        binding.tvTemporaryStorage.setOnClickListener(this);
        binding.include.titleView.setText("商品需求发布");
        linearLayoutManager = new LinearLayoutManager(this);
        addGoodsAdapter = new AddGoodsAdapter(this, null);
        binding.rv.setLayoutManager(linearLayoutManager);
        binding.rv.setAdapter(addGoodsAdapter);
        setData();
    }


    @Override
    protected void init() {
        opt2 = new ArrayList<>();
        opt3 = new ArrayList<>();
        if (demandGoodsEntityList == null) {
            demandGoodsEntityList = new ArrayList<>();
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.ll_add:
                DemandAddActivity.start(this);
                break;
            case R.id.ll_address:
                viewModel.getAddressModel();
                break;
            case R.id.ll_time:
                showTimePop();
                break;
            case R.id.tv_publish:
                if (demandGoodsEntityList == null || demandGoodsEntityList.size() == 0) {
                    Toast.makeText(DemandPublishActivity.this, "请添加一条商品需求", Toast.LENGTH_SHORT).show();
                    return;
                } else if (TextUtils.isEmpty(binding.editQualityRequire.getText())) {
                    MToast.showToast(DemandPublishActivity.this, "请输入质量要求");
                    return;
                } else if (TextUtils.isEmpty(binding.tvTime.getText())) {
                    MToast.showToast(DemandPublishActivity.this, "请选择需求时间");
                    return;
                } else if (TextUtils.isEmpty(binding.editUsage.getText())) {
                    MToast.showToast(DemandPublishActivity.this, "请输入用途描述");
                    return;
                } else if (TextUtils.isEmpty(binding.tvAddress.getText())) {
                    MToast.showToast(DemandPublishActivity.this, "请选择到货地方");
                    return;
                } else if (TextUtils.isEmpty(binding.editAddressDetail.getText())) {
                    MToast.showToast(DemandPublishActivity.this, "请输入详细地址");
                    return;
                } else if (TextUtils.isEmpty(binding.editConcat.getText())) {
                    MToast.showToast(DemandPublishActivity.this, "请输入联系人");
                    return;
                } else if (TextUtils.isEmpty(binding.editConcatNum.getText())) {
                    MToast.showToast(DemandPublishActivity.this, "请输入联系电话");
                    return;
                }
                viewModel.demandPublishEntity.get().setStatus("1");
                viewModel.saveDemand();
                break;
            case R.id.tv_temporary_storage:
                viewModel.demandPublishEntity.get().setStatus("0");
                viewModel.saveDemand();
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAttrEvent(DemandEvent event) {
        if (event.getMessageTag() == EVENT_ADD_GOOGS) {
            demandGoodsEntityList.add((DemandGoodsEntity) event.getObject());
            addGoodsAdapter.setDatas(demandGoodsEntityList);
            viewModel.demandPublishEntity.get().setGoodsList(demandGoodsEntityList);
            if (binding.cardList.getVisibility() == View.GONE) {
                binding.cardList.setVisibility(View.VISIBLE);
            }
        }
    }

    private void showDialog() {
        View view = View.inflate(getActivity(), R.layout.dialog_two_btn, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(getActivity(), 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
        //roundCornerDialog.setOnKeyListener(keylistener);//设置点击返回键Dialog不消失

        TextView tv_message = view.findViewById(R.id.tv_message);
        TextView tv_title = view.findViewById(R.id.tv_title);
        TextView tv_logout_confirm = view.findViewById(R.id.tv_logout_confirm);
        TextView tv_logout_cancel = view.findViewById(R.id.tv_logout_cancel);
        tv_title.setText("确认拨打电话");
        tv_title.setVisibility(View.VISIBLE);
        tv_message.setText("");

        //确定
        tv_logout_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });
        //取消
        tv_logout_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                roundCornerDialog.dismiss();
            }
        });
    }

    private void setData() {
        if (demandPublishEntity != null) {
            viewModel.demandPublishEntity.set(demandPublishEntity);
            demandGoodsEntityList = viewModel.demandPublishEntity.get().getGoodsList();
            addGoodsAdapter.setDatas(demandGoodsEntityList);
            if (binding.cardList.getVisibility() == View.GONE) {
                binding.cardList.setVisibility(View.VISIBLE);
            }
            binding.tvAddress.setText(viewModel.demandPublishEntity.get().getProvinceName() +
                    viewModel.demandPublishEntity.get().getCityName() +
                    viewModel.demandPublishEntity.get().getDistrictName());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM
            try {
                Date date = simpleDateFormat.parse(viewModel.demandPublishEntity.get().getNeedsTime());
                selectedDate = Calendar.getInstance();
                selectedDate.setTime(date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private static final int MSG_LOAD_DATA_UNIT = 0x0004;
    private static final int MSG_LOAD_SUCCESS_UNIT = 0x0005;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        thread = new Thread(() -> {
                            // 子线程中解析省市区数据
                            initJsonData();
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    showCityPop();
                    isLoaded = true;
                    thread = null;
                    break;
                case MSG_LOAD_FAILED:
                    break;
            }
        }
    };

    private void initJsonData() {
        //城市列表
        @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") List<AddressEntity<List<AddressEntity>>> cityList;
        //区域列表
        List<List<AddressEntity>> areaList;
        for (int x = 0; x < addressEntityList.size(); x++) {
            cityList = new ArrayList<>();
            areaList = new ArrayList<>();
            if (viewModel.demandPublishEntity.get() != null && viewModel.demandPublishEntity.get().getProvinceName() != null && viewModel.demandPublishEntity.get().getProvinceName().equals(addressEntityList.get(x).getName())) {
                cityPosition1 = x;
            }
            opt2.add(addressEntityList.get(x).getChildren());
            for (int i = 0; i < addressEntityList.get(x).getChildren().size(); i++) {
                cityList.add(addressEntityList.get(x).getChildren().get(i));
                List<AddressEntity> cityAreaList = new ArrayList<>();
                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (addressEntityList.get(x).getChildren().get(i).getChildren() == null
                        || addressEntityList.get(x).getChildren().get(i).getChildren().size() == 0) {
                    cityAreaList.add(null);
                } else {
                    cityAreaList.addAll(addressEntityList.get(x).getChildren().get(i).getChildren());
                }
                areaList.add(cityAreaList);
            }
            opt3.add(areaList);
        }
        if (viewModel.demandPublishEntity.get() != null) {
            if (viewModel.demandPublishEntity.get().getCityName() != null)
                for (int x2 = 0; x2 < opt2.size(); x2++) {
                    if (viewModel.demandPublishEntity.get().getCityName().equals(addressEntityList.get(cityPosition1).getChildren().get(x2).getName())) {
                        cityPosition2 = x2;
                        break;
                    }
                }
            if (viewModel.demandPublishEntity.get().getDistrictName() != null)
                for (int x3 = 0; x3 < opt3.get(cityPosition2).size(); x3++) {
                    if (viewModel.demandPublishEntity.get().getDistrictName().equals(addressEntityList.get(cityPosition1).getChildren().get(cityPosition2).getChildren().get(x3).getName())) {
                        cityPosition3 = x3;
                        break;
                    }
                }
        }
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }

    //地址
    public void showAddressPop(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> datas) {
        this.addressEntityList = datas;
        if (isLoaded) {
            showCityPop();
        } else {
            mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        }
    }

    @SuppressWarnings("unchecked")
    public void showCityPop() {
        //条件选择器
        CityPickView cityOption = new CityPickBuilder(DemandPublishActivity.this, (options1, options2, options3, v) -> {
            String areaName;
            if (opt3.get(options1).get(options2).get(options3) == null) {
                areaName = "";
            } else {
                areaName = opt3.get(options1).get(options2).get(options3).getName();
                cityPosition3 = options3;
                Objects.requireNonNull(viewModel.demandPublishEntity.get()).setDistrictName(areaName);
                Objects.requireNonNull(viewModel.demandPublishEntity.get()).setDistrictNo(opt3.get(options1).get(options2).get(options3).getNo());
            }
            String content = addressEntityList.get(options1).getName()
                    + opt2.get(options1).get(options2).getName()
                    + areaName;
            binding.tvAddress.setText(content);
            cityPosition1 = options1;
            cityPosition2 = options2;
            Objects.requireNonNull(viewModel.demandPublishEntity.get()).setProvinceName(addressEntityList.get(options1).getName());
            Objects.requireNonNull(viewModel.demandPublishEntity.get()).setProvinceNo(addressEntityList.get(options1).getId());
            Objects.requireNonNull(viewModel.demandPublishEntity.get()).setCityName(opt2.get(options1).get(options2).getName());
            Objects.requireNonNull(viewModel.demandPublishEntity.get()).setCityNo(opt2.get(options1).get(options2).getNo());
        }).build();
        cityOption.setPicker(addressEntityList, opt2, opt3);
        cityOption.setSelectOptions(cityPosition1, cityPosition2, cityPosition3);
        cityOption.show();
    }

    //时间选择器
    public void showTimePop() {
        setSoftWareHide();
        TimePickerView timePicker = new TimePickerBuilder(DemandPublishActivity.this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String format = sdf.format(date);
                try {
                    binding.tvTime.setText(format);
                    selectedDate.setTime(date);
                    Objects.requireNonNull(viewModel.demandPublishEntity.get()).setNeedsTime(format);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).build();
        timePicker.show();
        timePicker.setDate(selectedDate);
    }

    /**
     * 隐藏软键盘
     */
    private void setSoftWareHide() {
        InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(this.getWindow().getDecorView().getWindowToken(), 0);
        }
    }
}
